<template>
  <div class="emergency-manual">
    <!-- 统计信息 -->
    <div class="statistics-section">
      <div class="stat-cards">
        <div class="stat-card">
          <div class="stat-icon" style="background: #409EFF;">
            <i class="el-icon-document"></i>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ statistics.totalDocuments }}</div>
            <div class="stat-label">文档总数</div>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon" style="background: #67C23A;">
            <i class="el-icon-download"></i>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ statistics.totalDownloads }}</div>
            <div class="stat-label">总下载量</div>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon" style="background: #E6A23C;">
            <i class="el-icon-folder-opened"></i>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ statistics.categoryCount }}</div>
            <div class="stat-label">文档分类</div>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon" style="background: #F56C6C;">
            <i class="el-icon-star-on"></i>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ statistics.newThisMonth }}</div>
            <div class="stat-label">本月新增</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 搜索栏 -->
    <div class="search-section">
      <el-input
        v-model="searchKeyword"
        placeholder="搜索文档标题、作者、标签..."
        prefix-icon="el-icon-search"
        clearable
        @clear="handleSearch"
        @keyup.enter.native="handleSearch"
      >
        <el-button 
          slot="append" 
          icon="el-icon-search"
          @click="handleSearch"
        >搜索</el-button>
      </el-input>
    </div>

    <!-- 分类筛选 -->
    <div class="category-section">
      <div class="category-tabs">
        <div 
          v-for="category in categories" 
          :key="category.id"
          class="category-tab"
          :class="{ active: currentCategory === category.id }"
          @click="selectCategory(category.id)"
        >
          <i :class="category.icon"></i>
          <span>{{ category.name }}</span>
          <span v-if="categoryCounts[category.id]" class="count">
            ({{ categoryCounts[category.id] }})
          </span>
        </div>
      </div>
    </div>

    <!-- 排序和筛选 -->
    <div class="filter-section">
      <div class="filter-left">
        <span class="result-text">共 {{ filteredDocuments.length }} 个文档</span>
      </div>
      <div class="filter-right">
        <el-select 
          v-model="sortBy" 
          placeholder="排序方式" 
          size="small"
          @change="loadDocuments"
        >
          <el-option label="最新上传" value="date-desc"></el-option>
          <el-option label="最早上传" value="date-asc"></el-option>
          <el-option label="下载最多" value="download-desc"></el-option>
          <el-option label="下载最少" value="download-asc"></el-option>
          <el-option label="标题排序" value="title"></el-option>
        </el-select>
      </div>
    </div>

    <!-- 文档列表 -->
    <div class="documents-section">
      <div v-if="loading" class="loading-state">
        <i class="el-icon-loading"></i>
        <p>加载中...</p>
      </div>

      <div v-else-if="filteredDocuments.length === 0" class="empty-state">
        <i class="el-icon-document-delete"></i>
        <p>暂无文档</p>
      </div>

      <div v-else class="document-list">
        <div 
          v-for="doc in filteredDocuments" 
          :key="doc.id"
          class="document-card"
          @click="showDocumentDetail(doc)"
        >
          <div class="card-header">
            <div class="doc-type-badge" :class="`type-${doc.fileType}`">
              <i :class="getFileIcon(doc.fileType)"></i>
              <span>{{ doc.fileType.toUpperCase() }}</span>
            </div>
            <el-tag :type="getCategoryTagType(doc.category)" size="mini">
              {{ doc.categoryName }}
            </el-tag>
          </div>

          <div class="card-body">
            <div class="doc-title">{{ doc.title }}</div>
            <div class="doc-description">{{ doc.description }}</div>
            
            <div class="doc-tags">
              <el-tag 
                v-for="(tag, index) in doc.tags.slice(0, 3)" 
                :key="index"
                size="mini"
                effect="plain"
                type="info"
              >
                {{ tag }}
              </el-tag>
            </div>

            <div class="doc-meta">
              <div class="meta-item">
                <i class="el-icon-user"></i>
                <span>{{ doc.author }}</span>
              </div>
              <div class="meta-item">
                <i class="el-icon-time"></i>
                <span>{{ doc.uploadDate }}</span>
              </div>
            </div>
          </div>

          <div class="card-footer">
            <div class="footer-left">
              <span class="download-count">
                <i class="el-icon-download"></i>
                {{ doc.downloadCount }} 次下载
              </span>
              <span class="file-size">
                <i class="el-icon-document"></i>
                {{ doc.fileSize }}
              </span>
            </div>
            <div class="footer-right">
              <el-button 
                type="primary" 
                size="mini" 
                icon="el-icon-view"
                @click.stop="handlePreview(doc)"
              >
                预览
              </el-button>
              <el-button 
                type="success" 
                size="mini" 
                icon="el-icon-download"
                @click.stop="handleDownload(doc)"
              >
                下载
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 文档详情对话框 -->
    <el-dialog
      :title="currentDocument ? currentDocument.title : '文档详情'"
      :visible.sync="showDetailDialog"
      width="95%"
      top="5vh"
      center
      :close-on-click-modal="false"
      custom-class="document-detail-dialog"
    >
      <div v-if="currentDocument" class="detail-content">
        <div class="detail-section">
          <div class="detail-header">
            <div class="doc-type-badge large" :class="`type-${currentDocument.fileType}`">
              <i :class="getFileIcon(currentDocument.fileType)"></i>
              <span>{{ currentDocument.fileType.toUpperCase() }}</span>
            </div>
            <div class="detail-title">{{ currentDocument.title }}</div>
          </div>
        </div>

        <div class="detail-section">
          <div class="section-title">
            <i class="el-icon-info"></i>
            <span>基本信息</span>
          </div>
          <div class="info-grid">
            <div class="info-item">
              <span class="label">文档编号：</span>
              <span class="value">{{ currentDocument.id }}</span>
            </div>
            <div class="info-item">
              <span class="label">文档分类：</span>
              <el-tag :type="getCategoryTagType(currentDocument.category)" size="small">
                {{ currentDocument.categoryName }}
              </el-tag>
            </div>
            <div class="info-item">
              <span class="label">文件类型：</span>
              <span class="value">{{ currentDocument.fileType.toUpperCase() }}</span>
            </div>
            <div class="info-item">
              <span class="label">文件大小：</span>
              <span class="value">{{ currentDocument.fileSize }}</span>
            </div>
            <div class="info-item">
              <span class="label">发布单位：</span>
              <span class="value">{{ currentDocument.author }}</span>
            </div>
            <div class="info-item">
              <span class="label">上传日期：</span>
              <span class="value">{{ currentDocument.uploadDate }}</span>
            </div>
            <div class="info-item">
              <span class="label">更新日期：</span>
              <span class="value">{{ currentDocument.updateDate }}</span>
            </div>
            <div class="info-item">
              <span class="label">下载次数：</span>
              <span class="value highlight">{{ currentDocument.downloadCount }} 次</span>
            </div>
            <div class="info-item">
              <span class="label">文档状态：</span>
              <el-tag type="success" size="small">{{ currentDocument.status }}</el-tag>
            </div>
          </div>
        </div>

        <div class="detail-section">
          <div class="section-title">
            <i class="el-icon-document"></i>
            <span>文档简介</span>
          </div>
          <div class="document-description">
            {{ currentDocument.description }}
          </div>
        </div>

        <div class="detail-section">
          <div class="section-title">
            <i class="el-icon-collection-tag"></i>
            <span>文档标签</span>
          </div>
          <div class="tags-container">
            <el-tag 
              v-for="(tag, index) in currentDocument.tags" 
              :key="index"
              type="info"
              effect="plain"
              style="margin: 5px;"
            >
              {{ tag }}
            </el-tag>
          </div>
        </div>

        <div class="detail-actions">
          <el-button 
            type="primary" 
            icon="el-icon-view"
            size="large"
            @click="handlePreview(currentDocument)"
          >
            在线预览
          </el-button>
          <el-button 
            type="success" 
            icon="el-icon-download"
            size="large"
            @click="handleDownload(currentDocument)"
          >
            下载文档
          </el-button>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showDetailDialog = false">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 预览对话框 -->
    <el-dialog
      :title="`预览：${previewDocument ? previewDocument.title : ''}`"
      :visible.sync="showPreviewDialog"
      width="95%"
      top="5vh"
      center
      fullscreen
      :close-on-click-modal="false"
      custom-class="preview-dialog"
    >
      <div v-if="previewDocument" class="preview-content">
        <div class="preview-info">
          <i class="el-icon-info"></i>
          <span>这是文档预览窗口，实际使用时会显示文档内容</span>
        </div>
        <div class="preview-placeholder">
          <i :class="getFileIcon(previewDocument.fileType)" class="preview-icon"></i>
          <p class="preview-title">{{ previewDocument.title }}</p>
          <p class="preview-tip">文档预览功能需要集成文档预览服务</p>
          <el-button 
            type="primary" 
            icon="el-icon-download"
            @click="handleDownload(previewDocument)"
          >
            下载文档到本地查看
          </el-button>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showPreviewDialog = false">关闭预览</el-button>
        <el-button 
          type="primary" 
          icon="el-icon-download"
          @click="handleDownload(previewDocument)"
        >
          下载文档
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getDocumentList,
  getStatistics,
  downloadDocument,
  previewDocument,
  getDocumentCountByCategory,
  documentCategories
} from './service';

export default {
  name: 'EmergencyManual',

  data() {
    return {
      loading: false,
      searchKeyword: '',
      currentCategory: 'all',
      sortBy: 'date-desc',
      
      categories: documentCategories,
      documents: [],
      filteredDocuments: [],
      categoryCounts: {},
      
      statistics: {
        totalDocuments: 0,
        totalDownloads: 0,
        categoryCount: 0,
        newThisMonth: 0
      },
      
      showDetailDialog: false,
      currentDocument: null,
      
      showPreviewDialog: false,
      previewDocument: null
    };
  },

  methods: {
    // 获取文件图标
    getFileIcon(fileType) {
      const iconMap = {
        'pdf': 'el-icon-document',
        'doc': 'el-icon-document',
        'docx': 'el-icon-document',
        'xls': 'el-icon-tickets',
        'xlsx': 'el-icon-tickets',
        'ppt': 'el-icon-data-board',
        'pptx': 'el-icon-data-board'
      };
      return iconMap[fileType.toLowerCase()] || 'el-icon-document';
    },

    // 获取分类标签类型
    getCategoryTagType(category) {
      const typeMap = {
        'epidemic': 'danger',
        'rescue': 'warning',
        'management': '',
        'law': 'success',
        'guideline': 'info'
      };
      return typeMap[category] || '';
    },

    // 选择分类
    selectCategory(categoryId) {
      this.currentCategory = categoryId;
      this.loadDocuments();
    },

    // 搜索
    handleSearch() {
      this.loadDocuments();
    },

    // 加载文档列表
    loadDocuments() {
      this.loading = true;
      
      const params = {
        category: this.currentCategory,
        keyword: this.searchKeyword,
        sortBy: this.sortBy
      };

      getDocumentList(params).then(result => {
        this.loading = false;
        if (result.success) {
          this.documents = result.data;
          this.filteredDocuments = result.data;
        }
      }).catch(error => {
        this.loading = false;
        console.error('加载文档列表失败', error);
        this.showToast('加载失败，请重试', 'error');
      });
    },

    // 显示文档详情
    showDocumentDetail(doc) {
      this.currentDocument = doc;
      this.showDetailDialog = true;
    },

    // 预览文档
    handlePreview(doc) {
      // 关闭详情对话框
      this.showDetailDialog = false;
      
      previewDocument(doc.id).then(result => {
        if (result.success) {
          this.previewDocument = doc;
          this.showPreviewDialog = true;
          this.showToast('文档预览加载成功');
        }
      }).catch(error => {
        this.showToast(error.message || '预览失败', 'error');
      });
    },

    // 下载文档
    handleDownload(doc) {
      const loading = this.$loading({
        lock: true,
        text: '正在下载文档...',
        background: 'rgba(0, 0, 0, 0.7)'
      });

      downloadDocument(doc.id).then(result => {
        loading.close();
        if (result.success) {
          this.showToast(`《${doc.title}》下载成功`);
          // 更新本地文档的下载次数
          const docIndex = this.documents.findIndex(d => d.id === doc.id);
          if (docIndex > -1) {
            this.documents[docIndex].downloadCount = result.data.downloadCount;
          }
          
          // 模拟文件下载
          // 实际项目中这里应该触发真实的文件下载
          console.log('下载文档：', result.data.downloadUrl);
        }
      }).catch(error => {
        loading.close();
        this.showToast(error.message || '下载失败', 'error');
      });
    },

    // Toast提示
    showToast(message, type = 'success') {
      this.$notify({
        title: '',
        message: message,
        type: type,
        duration: 2000,
        position: 'top-right',
        offset: 60
      });
    },

    // 加载统计数据
    loadStatistics() {
      getStatistics().then(result => {
        if (result.success) {
          this.statistics = result.data;
        }
      }).catch(error => {
        console.error('加载统计数据失败', error);
      });
    },

    // 加载分类统计
    loadCategoryCounts() {
      getDocumentCountByCategory().then(result => {
        if (result.success) {
          this.categoryCounts = result.data;
        }
      }).catch(error => {
        console.error('加载分类统计失败', error);
      });
    }
  },

  mounted() {
    const loading = this.$loading({
      lock: true,
      text: '加载中...',
      background: 'rgba(0, 0, 0, 0.7)'
    });

    Promise.all([
      this.loadStatistics(),
      this.loadCategoryCounts(),
      this.loadDocuments()
    ]).finally(() => {
      loading.close();
    });
  }
};
</script>

<style scoped>
.emergency-manual {
  background: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 20px;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
}

/* 统计信息 */
.statistics-section {
  background: white;
  padding: 15px;
  margin-bottom: 10px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.stat-cards {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 10px;
}

.stat-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #f8f9fa;
  border-radius: 8px;
  padding: 12px 8px;
  text-align: center;
}

.stat-icon {
  width: 44px;
  height: 44px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 8px;
  flex-shrink: 0;
}

.stat-icon i {
  font-size: 20px;
  color: white;
}

.stat-info {
  width: 100%;
}

.stat-value {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 11px;
  color: #666;
  line-height: 1.3;
}

/* 搜索栏 */
.search-section {
  background: white;
  padding: 15px;
  margin-bottom: 10px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.search-section >>> .el-input__inner {
  border-radius: 20px 0 0 20px;
}

.search-section >>> .el-input-group__append {
  border-radius: 0 20px 20px 0;
  background: #409EFF;
  border-color: #409EFF;
  color: white;
}

/* 分类筛选 */
.category-section {
  background: white;
  padding: 10px 15px;
  margin-bottom: 10px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  overflow-x: auto;
  -webkit-overflow-scrolling: touch;
}

.category-tabs {
  display: flex;
  gap: 8px;
  min-width: max-content;
}

.category-tab {
  flex-shrink: 0;
  padding: 8px 15px;
  background: #f8f9fa;
  border-radius: 20px;
  cursor: pointer;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 13px;
  color: #666;
  border: 2px solid transparent;
}

.category-tab i {
  font-size: 14px;
}

.category-tab .count {
  font-size: 12px;
  color: #999;
}

.category-tab.active {
  background: #e7f4ff;
  color: #409EFF;
  border-color: #409EFF;
  font-weight: 600;
}

.category-tab:active {
  transform: scale(0.95);
}

/* 排序筛选 */
.filter-section {
  background: white;
  padding: 10px 15px;
  margin-bottom: 10px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-left {
  flex: 1;
}

.result-text {
  font-size: 13px;
  color: #666;
}

.filter-right {
  flex-shrink: 0;
}

/* 文档列表 */
.documents-section {
  background: white;
  padding: 15px;
  margin-bottom: 10px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.loading-state,
.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: #999;
}

.loading-state i,
.empty-state i {
  font-size: 64px;
  color: #ddd;
  margin-bottom: 15px;
}

.loading-state p,
.empty-state p {
  font-size: 14px;
  margin: 0;
}

.document-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.document-card {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 15px;
  cursor: pointer;
  transition: all 0.3s;
  border: 2px solid transparent;
}

.document-card:active {
  transform: scale(0.98);
  border-color: #409EFF;
  background: #e7f4ff;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.doc-type-badge {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 4px 10px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 600;
}

.doc-type-badge.large {
  padding: 8px 15px;
  font-size: 14px;
}

.doc-type-badge.type-pdf {
  background: #fee;
  color: #F56C6C;
}

.doc-type-badge.type-doc,
.doc-type-badge.type-docx {
  background: #e7f4ff;
  color: #409EFF;
}

.doc-type-badge.type-xls,
.doc-type-badge.type-xlsx {
  background: #f0f9ff;
  color: #67C23A;
}

.card-body {
  display: flex;
  flex-direction: column;
  gap: 10px;
  margin-bottom: 12px;
  padding-bottom: 12px;
  border-bottom: 1px solid #e4e7ed;
}

.doc-title {
  font-size: 15px;
  font-weight: 600;
  color: #333;
  line-height: 1.4;
}

.doc-description {
  font-size: 13px;
  color: #666;
  line-height: 1.5;
  max-height: 60px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
}

.doc-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.doc-meta {
  display: flex;
  gap: 15px;
  flex-wrap: wrap;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #999;
}

.meta-item i {
  font-size: 13px;
  color: #409EFF;
}

.card-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 10px;
}

.footer-left {
  flex: 1;
  display: flex;
  gap: 15px;
  flex-wrap: wrap;
}

.download-count,
.file-size {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #999;
}

.download-count i,
.file-size i {
  font-size: 13px;
  color: #67C23A;
}

.footer-right {
  display: flex;
  gap: 8px;
  flex-shrink: 0;
}

/* 详情对话框 */
.detail-content {
  padding: 10px 0;
}

.detail-section {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #f0f0f0;
}

.detail-section:last-child {
  border-bottom: none;
  margin-bottom: 0;
  padding-bottom: 0;
}

.detail-header {
  text-align: center;
  margin-bottom: 15px;
}

.detail-header .doc-type-badge {
  display: inline-flex;
  margin-bottom: 10px;
}

.detail-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  line-height: 1.4;
}

.section-title {
  display: flex;
  align-items: center;
  font-size: 15px;
  font-weight: 600;
  color: #333;
  margin-bottom: 12px;
  padding-left: 10px;
  border-left: 3px solid #409EFF;
}

.section-title i {
  font-size: 16px;
  margin-right: 6px;
  color: #409EFF;
}

.info-grid {
  display: grid;
  grid-template-columns: 1fr;
  gap: 12px;
}

.info-item {
  display: flex;
  align-items: center;
  font-size: 14px;
  background: #f8f9fa;
  padding: 10px 12px;
  border-radius: 6px;
}

.info-item .label {
  color: #666;
  min-width: 90px;
  flex-shrink: 0;
  font-weight: 500;
}

.info-item .value {
  color: #333;
  flex: 1;
}

.info-item .value.highlight {
  color: #409EFF;
  font-weight: 600;
}

.document-description {
  font-size: 14px;
  color: #333;
  line-height: 1.6;
  background: #f8f9fa;
  padding: 12px;
  border-radius: 6px;
  white-space: pre-wrap;
}

.tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.detail-actions {
  display: flex;
  gap: 10px;
  margin-top: 20px;
}

.detail-actions .el-button {
  flex: 1;
}

.dialog-footer {
  display: flex;
  gap: 10px;
  padding: 0;
}

.dialog-footer .el-button {
  flex: 1;
  margin: 0;
}

/* 预览对话框 */
.preview-content {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.preview-info {
  background: #e7f4ff;
  color: #409EFF;
  padding: 12px 15px;
  border-radius: 6px;
  margin-bottom: 15px;
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 13px;
}

.preview-info i {
  font-size: 16px;
  flex-shrink: 0;
}

.preview-placeholder {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #f8f9fa;
  border-radius: 8px;
  padding: 40px 20px;
  text-align: center;
}

.preview-icon {
  font-size: 80px;
  color: #409EFF;
  margin-bottom: 20px;
}

.preview-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 10px;
}

.preview-tip {
  font-size: 14px;
  color: #999;
  margin-bottom: 20px;
}

/* 对话框样式优化 */
.emergency-manual >>> .document-detail-dialog .el-dialog__body,
.emergency-manual >>> .preview-dialog .el-dialog__body {
  padding: 20px;
  max-height: calc(90vh - 120px);
  overflow-y: auto;
}

.emergency-manual >>> .preview-dialog .el-dialog__body {
  display: flex;
  flex-direction: column;
}
</style>

